package com.sky.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderedMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderedMapper orderedMapper;
    @Autowired
    private AddressBookServiceImpl addressBookService;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    WebSocketServer webSocketServer;


    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.判断地址是否为空
        AddressBook addressBook = addressBookService.getByid(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectById(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //3.向订单表插入数据
        //构建实体类对象
        Orders orders = new Orders();
        orders.setNumber(UUID.randomUUID().toString());//订单号
        orders.setUserId(BaseContext.getCurrentId());//下单用户ID
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态
        orders.setPayStatus(Orders.UN_PAID);//支付状态
        orders.setPhone(addressBook.getPhone());//手机号
        orders.setAddress(addressBook.getDetail());//详细地址
        orders.setConsignee(addressBook.getConsignee());//收货人
        //将前段传入的数据拷贝到orders对象中
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //向订单表插入数据
        orderedMapper.insert(orders);
        //4.向订单明细表插入多条数据
        //遍历购物车数据，将购物车数据插入到订单明细表
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            //创建订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        //批量插入订单明细数据
        orderDetailMapper.insertBatch(orderDetails);
        //5.删除购物车数据
        shoppingCartMapper.deleteAll(shoppingCart.getUserId());
        //封装VO数据返回
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Order
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderedMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderedMapper.update(orders);
    }

    @Override
    public PageResult pageList(OrdersPageQueryDTO ordersPageQueryDTO) {
//        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page page  = (Page) orderedMapper.pageList(ordersPageQueryDTO);
        long total = page.getTotal();
        List<Orders> result = page.getResult();
        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders orders : result) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            List<OrderDetail> orderDetails = orderDetailMapper.getByid(orders.getId());
            orderVO.setOrderDetailList(orderDetails);
            orderVOS.add(orderVO);
        }
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(orderVOS);
        return pageResult;
    }

    @Override
    public OrderVO getByid(Long id) {
        //根据传入的id查询订单表 再查询一下订单明细表
        Orders orders = orderedMapper.getByid(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getByid(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    @Override
    public void repetition(Long id) {
        //根据id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByid(id);
        ArrayList<ShoppingCart> shoppingCarts = new ArrayList<>();
        //将查询到的订单详情拷贝到购物车对象
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCarts.add(shoppingCart);
        }
        //将购物车对象批量插入到购物车表
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    @Override
    public void cancel(Long id) {
        //1.查询订单
        Orders orders = orderedMapper.getByid(id);
        //2.查询的订单判断是否存在 不存在则返回异常
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //3.判断订单状态是否能够取消 已接单不能取消 已派送不能取消  订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        if (orders.getStatus() >= Orders.CONFIRMED && orders.getStatus() <= Orders.COMPLETED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //4.更新订单状态
        orders.setCancelReason("用户取消");
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orderedMapper.update(orders);

    }

    @Override
    public OrderStatisticsVO statistics() {
        //分别查询 待接单数量 待派送数量 派送中数量
       Integer toBeConfirmed =  orderedMapper.getCountByStatus(Orders.TO_BE_CONFIRMED);
       Integer confirmCount =  orderedMapper.getCountByStatus(Orders.CONFIRMED);
       Integer deliveryCount =  orderedMapper.getCountByStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmCount);
        orderStatisticsVO.setDeliveryInProgress(deliveryCount);
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderedMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //1.查询订单
        Orders orders = orderedMapper.getByid(ordersRejectionDTO.getId());
        //2.判断订单状态只有在待接单状态才可以取消
        if (!orders.getStatus().equals(Orders.REFUND)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //3.修改订单状态
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orderedMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        //1.查询订单
        Orders orders = orderedMapper.getByid(id);
        //2.判断是否存在 订单状态只有在待派送状态才可以派送
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //3.封装对象 修改订单状态
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderedMapper.update(orders);
    }

    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        //1.查询订单 判断订单是否存在
        Orders orders = orderedMapper.getByid(ordersCancelDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.判断订单状态
        if (orders.getStatus()>Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setId(ordersCancelDTO.getId());
        orderedMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        //1.查询订单 判断订单是否存在
        Orders orders = orderedMapper.getByid(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.判断订单状态为4派送中才能完成
        if (!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //3.修改订单状态
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderedMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        //1.查询订单判断是不是空
        Orders orders = orderedMapper.getByid(id);
        if (orders == null){
            throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.使用websocket发送消息
       Map map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","用户催单了");
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

}
